from fastapi import APIRouter, HTTPException, Depends
from typing import List
from sqlalchemy.orm import Session
from schema import Lessee_schema
from controller import Lessee_controller
from database.db_init import get_db


router = APIRouter()


@router.post("/Lessee", response_model=Lessee_schema.Lessee, tags=["Lessee"])
async def create_Lessee(Lessee: Lessee_schema.Lessee, db: Session = Depends(get_db)):
    return Lessee_controller.create_Lessee(db, Lessee)


@router.get("/Lessee/{ID}", response_model=Lessee_schema.Lessee, tags=["Lessee"])
async def get_Lessee(ID: int, db: Session = Depends(get_db)):
    db_Lessee = Lessee_controller.get_Lessee(db, ID)
    if db_Lessee is None:
        raise HTTPException(status_code=404, detail="Lessee not found")
    return db_Lessee


@router.get("/Lessee", response_model=List[Lessee_schema.Lessee], tags=["Lessee"])
async def get_all_Lessee(db: Session = Depends(get_db)):
    all_db_Lessee = Lessee_controller.get_all_Lessee(db)
    if all_db_Lessee is None:
        raise HTTPException(status_code=404, detail="0 Lessee found, empty table")
    return all_db_Lessee


@router.put("/Lessee/{ID}", tags=["Lessee"])
async def update_Lessee(ID: int, field_name: str, field_value: str, db: Session = Depends(get_db)):
    try:
        db_Lessee = Lessee_controller.update_Lessee(db, ID, field_name, field_value)
        if db_Lessee is None:
            raise HTTPException(status_code=404, detail="Lessee not found")
        return db_Lessee
    except ValueError as error:
        raise HTTPException(status_code=400, detail=str(error))


@router.delete("/Lessee/{ID}", tags=["Lessee"])
async def delete_Lessee(ID: int, db: Session = Depends(get_db)):
    is_deleted = Lessee_controller.delete_Lessee(db, ID)
    if is_deleted is None:
        raise HTTPException(status_code=404, detail=f'Sample {ID} does not exist in database')
    else:
        return {'message': f'Successfully delete sample {ID}'}
